package sy.service.impl;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import sun.security.util.PropertyExpander.ExpandException;
import sy.bean.ComplaintBean;
import sy.bean.VisitorBean;
import sy.model.AppComplaint;
import sy.model.AppEquipment;
import sy.model.AppPlant;
import sy.model.BluetoothCard;
import sy.model.IotParkingOutException;
import sy.model.IotParkingURI;
import sy.model.IotPatrolURI;
import sy.model.IotTalkBackURI;
import sy.model.SysAccount;
import sy.model.SysBuilding;
import sy.model.SysOwnerRenterMapping;
import sy.model.SysProject;
import sy.model.SysUnit;
import sy.model.SysUser;
import sy.model.SysUserUnitMapping;
import sy.model.SysVisitor;
import sy.model.WYAccount;
import sy.model.WYAccountProjectMapping;
import sy.model.WYUser;
import sy.service.AppComplaintServiceI;
import sy.service.AppEquipmentServiceI;
import sy.service.AppPlantServiceI;
import sy.service.BluetoothCardServiceI;
import sy.service.IotParkingOutExceptionServiceI;
import sy.service.IotParkingURIServiceI;
import sy.service.IotPatrolURIServiceI;
import sy.service.SysAccountServiceI;
import sy.service.SysBuildingServiceI;
import sy.service.SysProjectServiceI;
import sy.service.SysUnitServiceI;
import sy.service.SysUserServiceI;
import sy.service.SysUserUnitMappingServiceI;
import sy.service.SysVisitorServiceI;
import sy.service.IotTalkBackURIServiceI;
import sy.service.WYAccountProjectMappingServiceI;
import sy.service.WYAccountServiceI;
import sy.service.WYBusinessServiceI;
import sy.service.WYUserServiceI;
import sy.util.CodeUtil;
import sy.util.DateUtil;
import sy.util.FileUpload;
import sy.util.HttpUtils;
import sy.util.JGpush;
import sy.util.JSInterface;
import sy.util.ResultJson;
import sy.util.XGInterface;
@Service("wyBusinessService")
public class WYBusinessServiceImpl implements WYBusinessServiceI{
	@Autowired
	WYAccountServiceI wyAccountService;
	@Autowired
	AppEquipmentServiceI appEquipmentService;
	@Autowired
	AppPlantServiceI appPlantService;
	@Autowired
	WYUserServiceI wyUserService;
	@Autowired
	AppComplaintServiceI appComplaintService;
	@Autowired
	SysVisitorServiceI sysVisitorService;
	@Autowired
	IotTalkBackURIServiceI iotTalkBackURIService;
	@Autowired
	IotParkingURIServiceI iotParkingURIService;
	@Autowired
	IotParkingOutExceptionServiceI iotParkingOutExceptionService;
	@Autowired
	IotPatrolURIServiceI iotPatrolURIService;
	@Autowired
	SysAccountServiceI sysAccountService;
	@Autowired
	SysUserServiceI sysUserService;
	@Autowired
	SysUserUnitMappingServiceI sysUserUnitMappingService;
	@Autowired
	WYAccountProjectMappingServiceI wyAccountProjectMappingService;
	@Autowired
	private SysUnitServiceI sysUnitService;
	@Autowired
	private SysBuildingServiceI SysBuildingService;
	@Autowired
	BluetoothCardServiceI bluetoothCardService;

	private int judgeToken(String token){
		WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
		if(wyAccount==null){
			return 400;//没有登录
		}
		Date loginTime = wyAccount.getLoginTime();
		if (loginTime == null) {
			return 400;//没有登录
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				long d = DateUtil.differDay(sdf.format(loginTime), sdf.format(new Date()));
				/**
				 * 当前时间跟上一次登录时间大于15天，则token过期
				 */
				if (d>15) {
					return 401;//token已过期
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	@Override
	public ResultJson getScanInformation(String token, String type, String code) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			if ("".equals(type) || type == null) {
				resultJson.setState(false);
				resultJson.setErrorCode(-1);
				resultJson.setMessage("缺少类型参数");
			} else {
				Map<String,Object> map = new HashMap<String,Object>();
				if ("equipment".equals(type)) {
					AppEquipment equipment = appEquipmentService.getAppEquipmentByCode(code);
					if (equipment != null) {
						map.put("equipment", equipment);
						map.put("type", type);
						resultJson.setState(true);
						resultJson.setErrorCode(200);
						resultJson.setResult(map);
					} else {
						resultJson.setState(false);
						resultJson.setErrorCode(-3);
						resultJson.setMessage("没有匹配的信息");
					}
				} else if ("plant".equals(type)){
					AppPlant plant = appPlantService.getAppPlantByCode(code);
					if (plant != null) {
						map.put("plant", plant);
						map.put("type", type);
						resultJson.setState(true);
						resultJson.setErrorCode(200);
						resultJson.setResult(map);
					} else {
						resultJson.setState(false);
						resultJson.setErrorCode(-3);
						resultJson.setMessage("没有匹配的信息");
					}
				} else {
					resultJson.setState(false);
					resultJson.setErrorCode(-2);
					resultJson.setMessage("条形码错误");
				}
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getMachineProject(String token) {
		ResultJson resultJson = new ResultJson();
		String uniqueCode = "project";
		IotTalkBackURI iotTalkBackURI = iotTalkBackURIService.getIotTalkBackURIByCode(uniqueCode);
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			String result = "";
			try {
				result  = HttpUtils.sendGetRest(iotTalkBackURI.getUri(), "GET");
			} catch (Exception e) {
				e.printStackTrace();
			}

			JSONObject obj = (JSONObject) JSONObject.parse(result);
			String state = obj.getString("state");
			/**************-1表示返回数据异常，0表示成功*******************/
			if (!"-1".equals(state)) {
				String data = obj.getString("data");
				JSONArray arry = JSONArray.parseArray(data);
				/**************没有数据返回时提示系统内部消息*******************/
				if( !arry.isEmpty()) {
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("projectList", arry);
					resultJson.setErrorCode(200);
					resultJson.setState(true);
					resultJson.setResult(map);
				} else {
					resultJson.setErrorCode(202);
					resultJson.setState(false);
					resultJson.setMessage("没有数据返回");
				}
			}else{
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("系统异常，请求失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}

		return resultJson;
	}

	@Override
	public ResultJson getMachineDevice(String ProjectCode, String token) {
		ResultJson resultJson = new ResultJson();
		String uniqueCode = "device";
		IotTalkBackURI iotTalkBackURI = iotTalkBackURIService.getIotTalkBackURIByCode(uniqueCode);
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			String result = "";
			Map<String, String> params = new HashMap<String, String>();
			params.put("ProjectCode", ProjectCode);
			result  = HttpUtils.sendPost(iotTalkBackURI.getUri(), params);

			JSONObject obj = (JSONObject) JSONObject.parse(result);
			String state = obj.getString("state");
			/**************-1表示返回数据异常，0表示成功*******************/
			if (!"-1".equals(state)) {
				String data = obj.getString("data");
				JSONArray arry = JSONArray.parseArray(data);
				/**************没有数据返回时提示系统内部消息*******************/
				if( !arry.isEmpty()) {
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("rows", arry);
					resultJson.setErrorCode(200);
					resultJson.setState(true);
					resultJson.setResult(map);
				} else {
					resultJson.setErrorCode(202);
					resultJson.setState(false);
					resultJson.setMessage("没有数据返回");
				}
			}else{
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("系统异常，请求失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}

		return resultJson;
	}

	@Override
	public ResultJson getProjectCycleAlarm(String ProjectCode, String Cycle, String token) {
		ResultJson resultJson = new ResultJson();
		String uniqueCode = "alarm";
		IotTalkBackURI iotTalkBackURI = iotTalkBackURIService.getIotTalkBackURIByCode(uniqueCode);
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			String result = "";
			Map<String, String> params = new HashMap<String, String>();
			params.put("ProjectCode", ProjectCode);//中海华庭
			params.put("Cycle", Cycle);
			result  = HttpUtils.sendPost(iotTalkBackURI.getUri(), params);

			JSONObject obj = (JSONObject) JSONObject.parse(result);
			String state = obj.getString("state");
			/**************-1表示返回数据异常，0表示成功*******************/
			if (!"-1".equals(state)) {
				String data = obj.getString("data");
				JSONArray arry = JSONArray.parseArray(data);
				/**************没有数据返回时提示系统内部消息*******************/
				if( !arry.isEmpty()) {
					resultJson.setErrorCode(200);
					resultJson.setState(true);
					resultJson.setResult(arry);
					resultJson.setMessage("成功");
				} else {
					resultJson.setErrorCode(202);
					resultJson.setState(false);
					resultJson.setResult(arry);
					resultJson.setMessage("没有数据返回");
				}
			}else{
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("系统异常，请求失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}

		return resultJson;
	}

	@Override
	public ResultJson getProjectSomeDayAlarm(String ProjectCode,String DeviceID, String Date, String token) {
		ResultJson resultJson = new ResultJson();
		String uniqueCode = "alarm";
		IotTalkBackURI iotTalkBackURI = iotTalkBackURIService.getIotTalkBackURIByCode(uniqueCode);

		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			String result = "";
			/************将前端传来的日期格式化为标准的格式（yyyy-MM-dd）*************/
			String date = DateUtil.formatDateYMD(Date);
			Map<String, String> params = new HashMap<String, String>();
			params.put("ProjectCode", ProjectCode);
			params.put("DeviceID", DeviceID);
			params.put("Date", date);
			result  = HttpUtils.sendPost(iotTalkBackURI.getUri(), params);

			JSONObject obj = (JSONObject) JSONObject.parse(result);
			String state = obj.getString("state");
			/**************-1表示返回数据异常，0表示成功*******************/
			if (!"-1".equals(state)) {
				String data = obj.getString("data");
				JSONArray arry = JSONArray.parseArray(data);
				/**************没有数据返回时提示系统内部消息*******************/
				if(  !arry.isEmpty() ) {
					resultJson.setErrorCode(200);
					resultJson.setState(true);
					resultJson.setResult(arry);
				} else {
					resultJson.setErrorCode(202);
					resultJson.setState(false);
					resultJson.setMessage("没有数据返回");
				}
			}else{
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("系统异常，请求失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson navparame(String ProjectCode, String token) {
		ResultJson resultJson = new ResultJson();
		String uniqueCode = "navparame";
		IotTalkBackURI iotTalkBackURI = iotTalkBackURIService.getIotTalkBackURIByCode(uniqueCode);

		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			String result = "";
			Map<String, String> params = new HashMap<String, String>();
			params.put("ProjectCode", ProjectCode);
			result  = HttpUtils.sendPost(iotTalkBackURI.getUri(), params);

			JSONObject obj = (JSONObject) JSONObject.parse(result);
			String state = obj.getString("state");
			/**************-1表示返回数据异常，0表示成功*******************/
			if (!"-1".equals(state)) {
				String data = obj.getString("data");
				JSONArray arry = JSONArray.parseArray(data);
				/**************没有数据返回时提示系统内部消息*******************/
				if(  !arry.isEmpty() ) {
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("rows", arry);
					resultJson.setErrorCode(200);
					resultJson.setState(true);
					resultJson.setResult(map);
				} else {
					resultJson.setErrorCode(202);
					resultJson.setState(false);
					resultJson.setMessage("没有数据返回");
				}
			}else{
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("系统异常，请求失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getRealdata(String ProjectCode,String DeviceID, String token) {
		ResultJson resultJson = new ResultJson();
		String uniqueCode = "realdata";
		IotTalkBackURI iotTalkBackURI = iotTalkBackURIService.getIotTalkBackURIByCode(uniqueCode);

		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			String result = "";
			Map<String, String> params = new HashMap<String, String>();
			params.put("ProjectCode", ProjectCode);
			params.put("DeviceID", DeviceID);
			result  = HttpUtils.sendPost(iotTalkBackURI.getUri(), params);

			JSONObject obj = (JSONObject) JSONObject.parse(result);
			String state = obj.getString("state");
			/**************-1表示返回数据异常，0表示成功*******************/
			if (!"-1".equals(state)) {
				String data = obj.getString("data");
				JSONArray arry = JSONArray.parseArray(data);
				/**************没有数据返回时提示系统内部消息*******************/
				if(  !arry.isEmpty() ) {
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("rows", arry);
					resultJson.setErrorCode(200);
					resultJson.setState(true);
					resultJson.setResult(map);
				} else {
					resultJson.setErrorCode(202);
					resultJson.setState(false);
					resultJson.setMessage("没有数据返回");
				}
			}else{
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("系统异常，请求失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getEnergy(String ProjectCode,String Date, String token) {
		ResultJson resultJson = new ResultJson();
		String uniqueCode = "energy";
		IotTalkBackURI iotTalkBackURI = iotTalkBackURIService.getIotTalkBackURIByCode(uniqueCode);

		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			String result = "";
			/************将前端传来的日期格式化为标准的格式（yyyy-MM-dd）*************/
			String date = DateUtil.formatDateYMD(Date);
			Map<String, String> params = new HashMap<String, String>();
			params.put("ProjectCode", ProjectCode);
			params.put("Date", date);
			result  = HttpUtils.sendPost(iotTalkBackURI.getUri(), params);

			JSONObject obj = (JSONObject) JSONObject.parse(result);
			String state = obj.getString("state");
			/**************-1表示返回数据异常，0表示成功*******************/
			if (!"-1".equals(state)) {
				String data = obj.getString("data");
				JSONArray arry = JSONArray.parseArray(data);
				/**************没有数据返回时提示系统内部消息*******************/
				if(  !arry.isEmpty() ) {
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("rows", arry);
					resultJson.setErrorCode(200);
					resultJson.setState(true);
					resultJson.setResult(map);
				} else {
					resultJson.setErrorCode(202);
					resultJson.setState(false);
					resultJson.setMessage("没有数据返回");
				}
			}else{
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("系统异常，请求失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson updateWYUser(String token, String name, String telephone) {
		// TODO Auto-generated method stub
		/**
		 * 先修改账号表的账号名,再修改个人信息的电话号码/姓名
		 * (有个人信息就代表账号已经被绑定)
		 */
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			if(wyAccount!=null){
				/****************只有更新电话号码时才会更新账号表的相关信息**********************/
				WYUser wyUser = wyUserService.getWYUserByWYAccountId(wyAccount.getId());
				if(telephone!=null && !"".equals(telephone)){
					wyAccount.setName(telephone);
					wyUser.setTelephone(telephone);
				}
				if(name!=null && !"".equals(name)){
					wyUser.setName(name);

				}
				resultJson.setState(true);
				resultJson.setErrorCode(200);
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson addComplaint(HttpServletRequest request,
			HttpServletResponse response, Map<String, Object> params) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		String token = (String) params.get("token");
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			/******************先上传图片再保存报事内容***********************/
			ResultJson fileUplaodJson = FileUpload.fileUpload(request, response);
			/**
			 * 判断投诉有没有文件上传
			 * 2表示没有文件上传，1表示上传失败，0表示上传成功
			 */
			if ("1".equals(fileUplaodJson.getFlag())) {
				resultJson.setState(false);
				resultJson.setMessage("上传图片/语音失败");
			} else {
				String type = (String) params.get("type");
				String equipmentCode = (String) params.get("equipmentCode");
				String inspectionPoint = (String) params.get("inspectionPoint");
				String remarks = (String) params.get("remarks");
				String urgency = (String) params.get("urgency");
				AppComplaint complaint = new AppComplaint();
				complaint.setCode(new CodeUtil().getCode());
				complaint.setEquipmentCode(equipmentCode);
				complaint.setType(type);
				complaint.setInspectionPoint(inspectionPoint);
				complaint.setRemarks(remarks);
				complaint.setUrgency(urgency);
				complaint.setImgUrl(fileUplaodJson.getMessage());
				complaint.setCreateTime(new Date());
				complaint.setStatus("0");//0表示待处理
				WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
				complaint.setWyAccount(wyAccount);
				try{
					appComplaintService.save(complaint);
					resultJson.setState(true);
					resultJson.setErrorCode(200);
					resultJson.setMessage("操作成功");
					/************报事成功后，推送消息给安管主任************/
					Map<String, String> jgPushParm = new HashMap<String, String>();
					jgPushParm.put("msg", "来自"+wyAccount.getWyRole().getName()+"的一条报事记录，请及时查看");
					jgPushParm.put("key", "complaint");
					if("安防".equals(type)){
						JGpush.jpushIOSByTag(jgPushParm, "AGM");
						JGpush.jpushAndroidByTag(jgPushParm, "AGM");
					}
				}catch(Exception e){
					resultJson.setState(false);
					resultJson.setErrorCode(201);
					resultJson.setMessage("系统异常,操作失败");
				}
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson listComplaint(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			List<ComplaintBean> dealList = new ArrayList<ComplaintBean>();//已处理报事
			List<ComplaintBean> notDealList = new ArrayList<ComplaintBean>();//待处理报事
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			/**************************获取安防事件详情为安管主任的权限，不是该角色不能查看*******************************/
			if(wyAccount.getWyRole()!=null && (wyAccount.getWyRole().getCode().contains("AGM")) || wyAccount.getWyRole().getCode().contains("projectManager")){

				List<AppComplaint> dealListComplaint = appComplaintService.getListByStatus("1");
				List<AppComplaint> notDealListComplaint = appComplaintService.getListByStatus("0");
				for(int i = 0; i<notDealListComplaint.size(); i++){
					String complaintUserName = "";
					WYUser wyComplaintUser = wyUserService.getWYUserByWYAccountId(notDealListComplaint.get(i).getWyAccount().getId());
					complaintUserName = wyComplaintUser.getName();
					ComplaintBean complainBean = new ComplaintBean();
					complainBean.setAppComplaint(notDealListComplaint.get(i));
					complainBean.setComplaintUserName(complaintUserName);
					notDealList.add(complainBean);
					if(i>20){
						break;
					}
				}

				for(int i = 0; i<dealListComplaint.size(); i++){
					String complaintUserName = "";
					WYUser wyComplaintUser = wyUserService.getWYUserByWYAccountId(dealListComplaint.get(i).getWyAccount().getId());
					complaintUserName = wyComplaintUser.getName();
					ComplaintBean complainBean = new ComplaintBean();
					complainBean.setAppComplaint(dealListComplaint.get(i));
					complainBean.setComplaintUserName(complaintUserName);
					if(dealListComplaint.get(i).getManageWYAccount()!=null){
						WYUser wyManageUser = wyUserService.getWYUserByWYAccountId(dealListComplaint.get(i).getManageWYAccount().getId());
						if(wyManageUser!=null){
							complainBean.setManageUserName(wyManageUser.getName());
						}
					}
					dealList.add(complainBean);
					if(i>20){
						break;
					}
				}

				/*for(AppComplaint complaint : complaintList){
				 *//**********0表示待处理，1表示已处理*************//*
					String complaintUserName = "";
					WYUser wyComplaintUser = wyUserService.getWYUserByWYAccountId(complaint.getWyAccount().getId());
					complaintUserName = wyComplaintUser.getName();
					ComplaintBean complainBean = new ComplaintBean();
					complainBean.setAppComplaint(complaint);
					complainBean.setComplaintUserName(complaintUserName);
					if("0".equals(complaint.getStatus())){
						notDealList.add(complainBean);
					}else{
						if(complaint.getManageWYAccount()!=null){
							WYUser wyManageUser = wyUserService.getWYUserByWYAccountId(complaint.getManageWYAccount().getId());
							if(wyManageUser!=null){
								complainBean.setManageUserName(wyManageUser.getName());
							}
						}
						dealList.add(complainBean);
					}
				}*/
				resultMap.put("deal", dealList);
				resultMap.put("notDeal", notDealList);
				resultJson.setState(true);
				resultJson.setErrorCode(200);
				resultJson.setResult(resultMap);
			}else{
				resultJson.setState(false);
				resultJson.setErrorCode(115);
				resultJson.setMessage("您没有该权限!");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson submitComplaint(HttpServletRequest request,HttpServletResponse response,String token,
			String manageRemarks, String workOrder) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			if(wyAccount.getWyRole()!=null && wyAccount.getWyRole().getCode().contains("AGM")){
				//判断是否有文件上传，再更新该报事情况
				ResultJson fileUplaodJson = FileUpload.fileUpload(request, response);
				/**
				 * 判断投诉有没有文件上传
				 * 2表示没有文件上传，1表示上传失败，0表示上传成功
				 */
				if ("1".equals(fileUplaodJson.getFlag())) {
					resultJson.setState(false);
					resultJson.setMessage("上传图片/语音失败");
				} else {
					AppComplaint complaint = appComplaintService.getAppComplaintByCode(workOrder);
					complaint.setManageImgUrl(fileUplaodJson.getMessage());
					complaint.setManageTime(new Date());
					complaint.setManageWYAccount(wyAccount);
					complaint.setStatus("1");
					complaint.setManageRemarks(manageRemarks);
					resultJson.setState(true);
					resultJson.setErrorCode(200);
					resultJson.setMessage("操作成功!");
				}
			}else{
				resultJson.setState(false);
				resultJson.setErrorCode(115);
				resultJson.setMessage("您没有该权限!");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getVisitorList(String token) {
		// TODO Auto-generated method stub 
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			//if(wyAccount.getWyRole()!=null && (wyAccount.getWyRole().getCode().contains("AG") || wyAccount.getWyRole().getCode().contains("projectManager"))){
			List<VisitorBean> visitorBeanList = new ArrayList<VisitorBean>();
			List<SysVisitor> list = sysVisitorService.list();
			List<String> sysAccountIds = new ArrayList<String>();
			List<String> wyAccountIds = new ArrayList<String>();
			for(SysVisitor visitor :list){
				if(visitor.getSysAccount()!=null){
					sysAccountIds.add(visitor.getSysAccount().getId());
				}
				if(visitor.getRegistor()!=null){
					wyAccountIds.add(visitor.getRegistor().getId());
				}
			}
			/**
			 * 得到业主/登记人姓名
			 */
			List<SysUser> sysUserList = sysUserService.listSysUserByAccountIds(sysAccountIds);
			List<WYUser> wyUserList = wyUserService.listWYUserByAccountId(wyAccountIds);
			for(SysVisitor visitor :list){
				VisitorBean bean = new VisitorBean();
				if(!"y".equals(visitor.getIsYZInvitation())){
					bean.setSysVisitor(visitor);
					for(SysUser sysUser :sysUserList){
						if(sysUser.getSysAccount()!=null && visitor.getSysAccount()!=null && visitor.getSysAccount().getId().equals(sysUser.getSysAccount().getId())){
							bean.setYzName(sysUser.getName());
							break;
						}
					}
					for(WYUser wyUser :wyUserList){
						if(wyUser.getWyAccount()!=null && visitor.getRegistor()!=null && visitor.getRegistor().getId().equals(wyUser.getWyAccount().getId())){
							bean.setRegistorName(wyUser.getName());
							break;
						}
					}
					visitorBeanList.add(bean);
				}
			}
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("rows", visitorBeanList);
			resultJson.setState(true);
			resultJson.setErrorCode(200);
			resultJson.setResult(map);
			/*}else{
				resultJson.setState(false);
				resultJson.setErrorCode(115);
				resultJson.setMessage("您没有该权限!");
			}*/
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson saveVisitor(String token, Map<String, Object> params) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			WYAccount registor = wyAccountService.getWYAccountByToken(token);
			if(registor!=null && "门岗".equals(registor.getWyRoleName())){
				int timeNo = (int)params.get("timeNo");
				String timeUnit = (String)params.get("timeUnit");
				SysVisitor visitor = new SysVisitor();
				visitor.setId(UUID.randomUUID().toString());
				visitor.setName((String)params.get("name"));
				visitor.setType((String)params.get("type"));
				visitor.setCertificateType((String)params.get("certificateType"));
				visitor.setCetificateNo((String)params.get("cetificateNo"));
				visitor.setTelephone((String)params.get("telephone"));
				visitor.setTimeUnit(timeUnit);
				visitor.setTimeNo(timeNo);
				visitor.setCarNo((String)params.get("carNo"));
				visitor.setAccessReason((String)params.get("accessReason"));
				visitor.setRegistor(registor);
				Date date = new Date();
				visitor.setAccessTime(date);//登记时间
				try{
					/**
					 * 业主验证后
					 */
					String yzId = (String) params.get("yzId");
					if(yzId != null && !"null".equals(yzId)){
						SysAccount sysAccount = sysAccountService.getSysAccountById(yzId);
						visitor.setSysAccount(sysAccount);
						visitor.setRoomNo((String)params.get("roomNo"));
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(date);
						int accessTimeNo = 0;
						if("小时".equals(timeUnit)){
							accessTimeNo = timeNo;
						}else if("天".equals(timeUnit)){
							accessTimeNo = timeNo * 24;
						}
						Date leaveTime = DateUtil.getTimeByHour(calendar, accessTimeNo);
						visitor.setLeaveTime(leaveTime);//离开时间
					}
					sysVisitorService.save(visitor);
					resultJson.setState(true);
					resultJson.setErrorCode(200);
				}catch(Exception e){
					resultJson.setState(false);
					resultJson.setErrorCode(201);
				}
			}else{
				resultJson.setState(false);
				resultJson.setErrorCode(115);
				resultJson.setMessage("没有操作权限");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getParkingOutException(String token) {
		// TODO Auto-generated method stub
		/**
		 * 先从捷顺获取异常放行记录，再把记录的id同步到本地异常表，记录安管主任处理异常记录
		 */
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {//iotParkingURIService
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			if(wyAccount.getWyRole()!=null && (wyAccount.getWyRole().getCode().contains("AGM") || wyAccount.getWyRole().getCode().contains("projectManager"))){
				//iotParkingOutExceptionService.updateDate();
				List<IotParkingOutException> list = iotParkingOutExceptionService.list();
				Map<String,Object> resultMap = new HashMap<>();
				resultMap.put("total", list.size());
				resultMap.put("rows", list);
				resultJson.setState(true);
				resultJson.setErrorCode(200);
				resultJson.setResult(resultMap);

				/*				IotParkingURI iotParkingURI = iotParkingURIService.getIotParkingURIByUniqueCode("parkOutException");
				try {
					String uri = "http://202.105.104.105:8003/park_car_out_exceptions";
					if(iotParkingURI!=null && !"".equals(iotParkingURI.getUri())){
						uri = iotParkingURI.getUri();
					}
					String result = HttpUtils.sendGetRest(uri,"GET");
					if(!"null".equals(result)){
						JSONArray arr = JSONArray.parseArray(result);
				 *//************************把获取的当天异常放行记录同步到本地异常表*****************************//*
						List<IotParkingOutException> exceptionList = new ArrayList<IotParkingOutException>();
						for(int i = 0; i<arr.size(); i++){
							IotParkingOutException exception = new IotParkingOutException();
							String exceptionId = arr.getJSONObject(i).getString("ID");
							exception.setOutExceptionId(exceptionId);
							exceptionList.add(exception);
						}
						try{
							iotParkingOutExceptionService.saveList(exceptionList);
						}catch(Exception e){
							System.out.println(e);
						}
						resultJson.setState(true);
						resultJson.setErrorCode(200);
						resultJson.setResult(arr);
					}else{
						resultJson.setState(false);
						resultJson.setErrorCode(202);
						resultJson.setResult(new ArrayList<>());
						resultJson.setMessage("没有相关数据返回");
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					resultJson.setState(false);
					resultJson.setErrorCode(201);
					resultJson.setMessage("系统异常，操作失败");
				}*/
			}else{
				resultJson.setState(false);
				resultJson.setErrorCode(115);
				resultJson.setMessage("您没有该权限!");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getParkingEntryLog(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			String itemId = "6c7fb5de82694ade885ab07883738670";
			String equipmentId = "1cb5de82694ade885ab07883738ac3";
			String state = "in"; 
			String startTime = "2017-09-02 11:11:11";
			String endTime = "2017-09-05 11:11:11";
			String result = JSInterface.getEntryLog(itemId, equipmentId, state, startTime, endTime, "");
			JSONObject obj = JSONObject.parseObject(result);
			String resultCode = obj.getString("resultCode");
			/**
			 * 113:无效的令牌或令牌过期
			 * 118:客户ip不存在或ip未绑定或登录超时
			 * 获取新的token
			 */
			if(Integer.parseInt(resultCode)==113){
				result = JSInterface.getEntryLog(itemId, equipmentId, state, startTime, endTime, JSInterface.getAccessToken());
			}
			JSONObject resultObj = JSONObject.parseObject(result);
			resultCode = obj.getString("resultCode");
			if(Integer.parseInt(resultCode)==0){ //0：成功
				String dataItems = resultObj.getString("dataItems");
				JSONArray arryDataItems = JSONArray.parseArray(dataItems);
				resultJson.setState(true);
				resultJson.setErrorCode(200);
				resultJson.setResult(arryDataItems);
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson updateParkingOutExceptionStatus(String token,
			String exceptionId, String status) {
		// TODO Auto-generated method stub 
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			if(wyAccount.getWyRole()!=null && wyAccount.getWyRole().getCode().contains("AGM")){
				IotParkingOutException iotParkingOutException = iotParkingOutExceptionService.getByOutExceptionId(exceptionId);
				if(iotParkingOutException!=null){
					iotParkingOutException.setHandleTime(new Date());
					iotParkingOutException.setStatus(status);
					iotParkingOutException.setWyAccount(wyAccount);
					resultJson.setState(true);
					resultJson.setErrorCode(200);
				}else{
					resultJson.setState(false);
					resultJson.setErrorCode(116);
					resultJson.setMessage("记录不存在");
				}
			}else{
				resultJson.setState(false);
				resultJson.setErrorCode(115);
				resultJson.setMessage("您没有该权限!");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getPatrolCollectNodes(String token, int limit) {
		// TODO Auto-generated method stub
		/**
		 * 获取
		 * 请求示例：https://192.168.200.111:8443/zhwy/rest/v1/trails/real?token=6a29b7d7bd09472f873637212c5273dd&limit=4
		 */
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			if(wyAccount.getWyRole()!=null && wyAccount.getWyRole().getCode().contains("AGM")){
				IotPatrolURI iotPatrolURI = iotPatrolURIService.getIotPatrolURIByCode("trailsReal");
				String url = "https://192.168.200.111:8443/zhwy/rest/v1/trails/real";
				try {
					if(iotPatrolURI!=null){
						if(iotPatrolURI.getUri()!=null && iotPatrolURI.getUri().length()>0){
							url = iotPatrolURI.getUri();
						}
					}
					String patrolToken = iotPatrolURI.getToken();
					String uri = url+"?token="+patrolToken+"&areaId=2";
					String result = HttpUtils.sendGetRest(uri, "GET");
					/********************http响应为400时，表示token不存在或者过期，需要重新请求********************/
					if(result.contains("httpResponseCode")){
						Date nowDate = new Date();
						patrolToken = XGInterface.getRequestToken();
						iotPatrolURIService.updateRemoteInfo(patrolToken, nowDate);
						//uri = url+"?token="+patrolToken+"&limit="+limit+"&startTime="+URLEncoder.encode(currentTime)+"&endTime="+URLEncoder.encode(currentTime);
					}
					uri = url+"?token="+patrolToken+"&areaId=2";
					result = HttpUtils.sendGetRest(uri, "GET");
					JSONArray jsonArr = JSONArray.parseArray(result);
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("collectNodes", jsonArr);
					resultJson.setState(true);
					resultJson.setErrorCode(200);
					resultJson.setResult(map);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				resultJson.setState(false);
				resultJson.setErrorCode(115);
				resultJson.setMessage("您没有该权限!");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getPatrolCollectProgress(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			if(wyAccount.getWyRole()!=null && (wyAccount.getWyRole().getCode().contains("AGM") || wyAccount.getWyRole().getCode().contains("projectManager"))){
				/**
				 * 巡更进度：
				 *1.得到某个组织下的巡更人员的考核记录
				 *2.再根据人员获取考核统计
				 */

				try {

					IotPatrolURI planChecksIotPatrolURI = iotPatrolURIService.getIotPatrolURIByCode("planChecks");
					IotPatrolURI reportIotPatrolURI = iotPatrolURIService.getIotPatrolURIByCode("planChecksReport");

					String patrolToken = planChecksIotPatrolURI.getToken();

					String currentFirstTime = DateUtil.getCurrentDateFirstTime();
					String currentLastTime = DateUtil.getCurrentDateLastTime();

					String planChecksUrl = "https://192.168.200.111:8443/zhwy/rest/v1/planChecks";
					if(planChecksIotPatrolURI!=null){
						if(planChecksIotPatrolURI.getUri()!=null && planChecksIotPatrolURI.getUri().length()>0){
							planChecksUrl = planChecksIotPatrolURI.getUri();
						}
					}
					/************************************获取测试组的考核记录**********************************************/
					String planChecksUri = planChecksUrl + "?token="+patrolToken+"&areaId=2"+"&startTime="+URLEncoder.encode(currentFirstTime)+"&endTime="+URLEncoder.encode(currentLastTime);
					String planChecksResult = HttpUtils.sendGetRest(planChecksUri, "GET");
					JSONObject planChecksObj = JSONObject.parseObject(planChecksResult);//处理结果
					String httpResponseCode = planChecksObj.getString("httpResponseCode");
					if("400".equals(httpResponseCode)){
						Date nowDate = new Date();
						patrolToken = XGInterface.getRequestToken();
						iotPatrolURIService.updateRemoteInfo(patrolToken, nowDate);
						planChecksUri = planChecksUrl + "?limit=5&token="+patrolToken;
						planChecksResult = HttpUtils.sendGetRest(planChecksUri, "GET");
						planChecksObj = JSONObject.parseObject(planChecksResult);
					}
					String planChecksRows = planChecksObj.getString("rows");
					JSONArray arrRows = JSONArray.parseArray(planChecksRows);
					if(!arrRows.isEmpty()){
						List<Map<String, Object>> userList = new ArrayList<>();
						List<Map<String, Object>> planChecksList = new ArrayList<Map<String, Object>>();
						for(int i =0; i<arrRows.size(); i++){
							Map<String, Object> mapObj = new HashMap<String,Object>();
							JSONObject inspObj = (JSONObject) arrRows.get(i);

							Long userId = Long.parseLong(inspObj.getString("userId"));
							String nickname = inspObj.getString("nickname");

							boolean flag = false;
							for(Map<String, Object> map : userList){
								Long usrId = (Long) map.get("userId");
								if(String.valueOf(usrId).equals(String.valueOf(userId))){
									flag = true;
									break;
								}
							}
							if(!flag){
								mapObj.put("userId", userId);//巡检人员id
								mapObj.put("nickname", nickname);//巡检人员名称
								userList.add(mapObj);
							}
							/**
							 * 得到巡检人员考核情况
							 */
							Map<String, Object> planChecksMap = new HashMap<String,Object>();

							planChecksMap.put("userId", userId);//巡检人员id
							planChecksMap.put("collectNodeId", inspObj.getString("collectNodeId"));
							planChecksMap.put("nodeName", inspObj.getString("nodeName"));
							planChecksMap.put("startTime", inspObj.getString("startTime"));
							planChecksMap.put("endTime", inspObj.getString("endTime"));
							planChecksMap.put("arriveTime", inspObj.getString("arriveTime"));
							planChecksMap.put("arriveType", inspObj.getString("arriveType"));
							planChecksList.add(planChecksMap);
							//mapObj.put("planChecksList", planChecksList);//巡检工作计划信息
						}

						String reportUrl = "https://192.168.200.111:8443/zhwy/rest/v1/planChecks/report";
						if(reportIotPatrolURI!=null){
							if(reportIotPatrolURI.getUri()!=null && reportIotPatrolURI.getUri().length()>0){
								reportUrl = reportIotPatrolURI.getUri();
							}
						}
						List<Map<String,Object>> progressList = new ArrayList<>();
						for(Map<String,Object> map : userList){
							List<Map<String,Object>> userCheckedList = new ArrayList<>();
							Long userId = (Long) map.get("userId");
							String reportUri = reportUrl + "?token="+patrolToken+"&statType=1&userId="+userId+"&startTime="+URLEncoder.encode(currentFirstTime)+"&endTime="+URLEncoder.encode(currentLastTime);
							String reportResult = HttpUtils.sendGetRest(reportUri, "GET");
							JSONArray reportArr = JSONArray.parseArray(reportResult);
							if(!"".equals(reportArr) && !reportArr.isEmpty()){
								map.put("progress", reportArr.getJSONObject(0).get("arriveCount") + "/"+reportArr.getJSONObject(0).get("count"));//总进度
								map.put("count", reportArr.getJSONObject(0).get("count"));//已巡检定点总数
							}else{
								map.put("progress", 0 + "/"+ 0);//总进度
								map.put("count", 0);//已巡检定点总数
							}

							for(Map<String,Object> map1 : planChecksList){
								if(userId.equals(map1.get("userId"))){
									userCheckedList.add(map1);
								}
							}
							map.put("planChecksList", userCheckedList);
							progressList.add(map);
						}

						Map<String,Object> map = new HashMap<String,Object>();
						map.put("progressList", progressList);
						resultJson.setState(true);
						resultJson.setErrorCode(200);
						resultJson.setResult(map);
					}else{
						resultJson.setState(false);
						resultJson.setErrorCode(202);
					}
				} catch(Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				resultJson.setState(false);
				resultJson.setErrorCode(115);
				resultJson.setMessage("您没有该权限!");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getYZUnitByName(String token, String yzName) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			SysUser sysUser = sysUserService.getSysUserByName(yzName);
			List<String> address = new ArrayList<String>();
			if(sysUser!=null){
				List<SysUserUnitMapping> sysUserUnitMappingList =  sysUserUnitMappingService.listSysUserUnitMappingByOwnerId(sysUser.getId());
				if(!sysUserUnitMappingList.isEmpty()){
					for(SysUserUnitMapping obj:sysUserUnitMappingList){
						String addr = "";
						SysUnit sysUnit = obj.getSysUnit();
						if(sysUnit!=null){
							SysBuilding sysBuilding = obj.getSysUnit().getSysBuilding();
							if(sysBuilding!=null){
								SysProject sysProject = sysBuilding.getSysProject();
								if(sysProject!=null){
									addr += sysProject.getName()+sysBuilding.getName()+sysUnit.getName();
								}
							}
						}
						address.add(addr);
					}
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("address", address);
					map.put("yzId", sysUser.getSysAccount().getId());
					resultJson.setState(true);
					resultJson.setErrorCode(200);
					resultJson.setResult(map);
				}else{
					resultJson.setState(false);
					resultJson.setErrorCode(117);
					resultJson.setMessage("业主没有相关房址信息！");
				}
			}else{
				resultJson.setState(false);
				resultJson.setErrorCode(114);
				resultJson.setMessage("业主不存在！");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			case 400:
				resultJson.setMessage("您已退出登录，请重新登录");
				break;
			case 401:
				resultJson.setMessage("token已过期，请重新登录");
				break;
			default:break;
			}
		}
		return resultJson;
	}


	/***************************门禁服务*********************************/
	@Override
	public ResultJson getDoorList(String wyAccountId,String projectId) {

		ResultJson resultJson = new ResultJson();
		List<SysUnit> unitListResult =  new ArrayList<SysUnit>();
		List<SysBuilding> buildingListResult =  new ArrayList<SysBuilding>();
		List<SysProject> projectListResult = new ArrayList<SysProject>();

		List<WYAccountProjectMapping> wyAccountProjectMappingList = wyAccountProjectMappingService.listWYAccountProjectMappingByProjectAndAccount(wyAccountId, projectId);
		for(WYAccountProjectMapping projectList : wyAccountProjectMappingList){
			List<SysBuilding> buildList = SysBuildingService.getBuildingByProject(projectList.getSysProject().getId());
			for(SysBuilding build : buildList){
				List<SysUnit> unitList = sysUnitService.listSysUnitByKey(build.getId());
				for(SysUnit unit : unitList){
					unitListResult.add(unit);
				}
				buildingListResult.add(build);
			}
			projectListResult.add(projectList.getSysProject());
		} 

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("unitList", unitListResult);

		resultJson.setState(true);
		resultJson.setResult(resultMap);
		resultJson.setErrorCode(200);
		resultJson.setMessage("返回成功");
		return resultJson;
	}

	@Override
	public ResultJson bindBluetoothCard(Map<Object, Object> param) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		String address = (String)param.get("address");
		String accountId = (String)param.get("accountId");
		BluetoothCard obj = bluetoothCardService.getBluetoothCardByAddress(address,accountId);
		if(obj == null){
			BluetoothCard bluetoothCard = new BluetoothCard();
			bluetoothCard.setAccountId((String)param.get("accountId"));
			bluetoothCard.setCurrentCardStr((String)param.get("currentCardStr"));
			bluetoothCard.setName((String)param.get("name"));
			bluetoothCard.setIdentity((String)param.get("identity"));
			bluetoothCard.setAddress(address);
			bluetoothCard.setCommunitySign((String)param.get("communitySign"));
			bluetoothCard.setModel((String)param.get("model"));
			bluetoothCard.setVersion((String)param.get("version"));
			if(param.get("rssi") != null){
				bluetoothCard.setRssi(Integer.parseInt((String)param.get("rssi")));
			}
			try{
				bluetoothCardService.save(bluetoothCard);
				resultJson.setState(true);
				resultJson.setErrorCode(200);
			}catch(Exception e){
				resultJson.setState(false);
				resultJson.setErrorCode(201);
			}
		}else{
			obj.setCurrentCardStr((String)param.get("currentCardStr"));
			obj.setName((String)param.get("name"));
			obj.setAddress(address);
			obj.setCommunitySign((String)param.get("communitySign"));
			obj.setModel((String)param.get("model"));
			obj.setVersion((String)param.get("version"));
			if(param.get("rssi") != null){
				obj.setRssi(Integer.parseInt((String)param.get("rssi")));
			}
			resultJson.setState(true);
			resultJson.setErrorCode(200);
		}
		return resultJson;
	}

	@Override
	public ResultJson geBluetoothCardList(String accountId) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		List<BluetoothCard> list = bluetoothCardService.list(accountId);
		Map<String,Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", list);
		resultJson.setState(true);
		resultJson.setErrorCode(200);
		resultJson.setResult(map);
		return resultJson;
	}

	@Override
	public ResultJson delBluetoothCard(String address,String accountId) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		try{
			bluetoothCardService.deleteByAddress(address,accountId);
			resultJson.setState(true);
			resultJson.setErrorCode(200);
		}catch(Exception e){
			resultJson.setState(false);
			resultJson.setErrorCode(201);
		}
		return resultJson;
	}
}
